package xj.toolkit.benchmark.mockclient.ssl;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.UUID;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;

import com.google.common.io.ByteStreams;

import xj.toolkit.benchmark.mockclient.BaseHttpClient;

public class BaseHttpsClient {

	private static final Logger logger = LoggerFactory
			.getLogger(BaseHttpClient.class);


	public String post(String url, byte[] body, String contentType, int msgCode)
			throws Exception {
//		TrustManager[] tm = { new HTTPSTrustManager() };    
//        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");    
//        sslContext.init(null, tm, new java.security.SecureRandom());    
//          
//        // 从上述SSLContext对象中得到SSLSocketFactory对象     
        SSLSocketFactory ssf = getSSLContext().getSocketFactory();   
		
		//HTTPSTrustManager.allowAllSSL();
		HttpsURLConnection conn = (HttpsURLConnection) new URI(url).toURL()
				.openConnection();

		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", contentType);
		conn.setRequestProperty("Msg", "" + msgCode);
		conn.setRequestProperty("uuid", UUID.randomUUID().toString());
		conn.setRequestProperty("V", "" + 0);
		conn.getOutputStream().write(body);

		contentType = conn.getContentType();
		String encoding = "utf-8";
		if (contentType != null && contentType.indexOf("charset=") > 0) {
			encoding = contentType.split("charset=")[1];
		}

		InputStream is = conn.getInputStream();
		byte[] resp = ByteStreams.toByteArray(is);
		conn.disconnect();
		return new String(resp, encoding);
	}

	public static SSLContext getSSLContext(){
        SSLContext context = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream in = new ClassPathResource("./keyStore/cacert.pem").getInputStream();
            Certificate ca = cf.generateCertificate(in);
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setCertificateEntry("ca", ca);
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keystore);
            // Create an SSLContext that uses our TrustManager
            context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);
        } catch (Exception e){
            e.printStackTrace();
        }
        return context;
    }
	
}
